﻿using System;
using System.Collections.Generic;

namespace Xtreme.Json
{
  public static class JsonDeserializer
  {
    public static T FromJson<T>(this string json) where T: class
    {
      var parser = new JsonParser();
      return parser.Parse<T>(json);
    }

    public static Type ElementType(this Type type)
    {
      Type elementType = type.GetElementType();
      if (elementType != null)
      {
        type = elementType;
      }
      else if (type.IsGenericType)
      {
        Type definition = type.GetGenericTypeDefinition();
        if (definition == typeof(Nullable<>) || definition == typeof(IEnumerable<>) || definition == typeof(IList<>))
        {
          type = type.GenericTypeArguments[0];
        }
        else if (definition == typeof(IDictionary<,>))
        {
          type = typeof(KeyValuePair<,>).MakeGenericType(type.GetGenericArguments());
        }
      }
      return type;
    }

    public static void Add<TK, TV>(this ICollection<KeyValuePair<TK, TV>> dictionary, KeyValuePair<TK, TV> entry)
    {
      dictionary.Add(entry);
    }

    public static T Cast<T>(this object obj)
      where T : class
    {
      return (T)obj;
    }
  }
}